﻿using CommonModel.Util;
using GXRTBTC.PublicClassLibrary.Model;
using NewLife.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace GXRTBTC.PublicClassLibrary.Util
{
    /// <summary>
    /// http请求类
    /// 针对科江新远场的请求，服务端只能同时连接一个socket
    /// 所以为了确保每次连接后都保证能释放掉
    /// 所以用此类
    /// </summary>
    public class HttpClientHelper : IDisposable
    {
        private readonly HttpClient _httpClient;

        public HttpClientHelper()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(5);
        }

        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<Dictionary<string, Object>> Get(string url)
        {
            Dictionary<string, Object> rs = new() { { "return_code", -1 }, { "return_msg", "" }, { "data", "" } };
            try
            {
                //Timeout默认值是 100,000 毫秒（100 秒）。若要设置无限超时，请将属性值设置为 InfiniteTimeSpan
                //client.Timeout = TimeSpan.FromMinutes(10);

                //每一个api资源都有一个对应的网关地址
                HttpResponseMessage response = _httpClient.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)
                {
                    rs["data"] = await response.Content.ReadAsStringAsync();
                    rs["return_code"] = 0;
                }
                else
                {
                    rs["return_msg"] = "Get请求[" + url + "]异常";
                }
            }
            catch (Exception e)
            { 
                Console.WriteLine("get请求异常，" + e.Message);
                rs["return_msg"] = e.Message;
            }
            return rs;
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public async Task<Dictionary<string, Object>> Post(string url, string data, string contentType = "application/json")
        {
            Dictionary<string, Object> rs = new() { { "return_code", -1 }, { "return_msg", "" }, { "data", "" } };
            try
            {
                //var content = new StringContent(data, Encoding.UTF8, "application/json");

                //在使用编码方法（Encoding.GetEncoding("GB2312")）之前，对编码进行注册
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                var content = new StringContent(data, Encoding.GetEncoding(TransForm.encode), contentType);

                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    rs["data"] = await response.Content.ReadAsStringAsync();
                    rs["return_code"] = 0;
                }
                else
                {
                    rs["return_msg"] = "Post请求[" + url + "]异常";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("post请求异常，" + e.Message);
                rs["return_msg"] = e.Message;
            }
            return rs;
        }

        public void Dispose()
        {
            try
            {
                _httpClient.Dispose();
            }
            catch { }
        }
    }
}
